package com.lagou.client;

import com.lagou.boot.ConsumerBoot;
import com.lagou.handler.UserClientHandler;
import com.lagou.protocol.RpcRequest;
import com.lagou.serializer.JSONSerializer;
import com.lagou.serializer.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 13771
 * @date 2020/8/31 11:30
 * @description
 */
public class RPCConsumer {
    //1.创建一个线程池对象  --它要处理我们自定义事件
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //2.声明一个自定义事件处理器  UserClientHandler
    private static UserClientHandler userClientHandler;

    private static int resultPort = 0;

    //public static ZkClient zkClient = new ZkClient("127.0.0.1:2181");

    //3.初始化客户端
    public static void initClient() throws InterruptedException {
        //1) 初始化UserClientHandler
        userClientHandler = new UserClientHandler();

        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });



        //父节点路径
        //服务端集群
        List<String> serverList = new ArrayList<String>();
        String root = "/rpcServer";
        List<String> childrens = ConsumerBoot.zkClient.getChildren(root);
        long tempTime = 5000L;
        for (String children : childrens){
            String path = root + "/" +children; //子节点完整路径 /rpcServer/8998
            if (ConsumerBoot.zkClient.readData(path) == null){ //如果子节点下数据为null，则将请求路由到该服务器
                resultPort = Integer.parseInt(children);
                System.out.println("该服务器实例未连接客户端，优先路由该服务器实例");
                break;
            }else {
                String nodeValue = ConsumerBoot.zkClient.readData(path);  //节点值 responseTime,endTime
                long responseTime = Long.parseLong(nodeValue.split(",")[0]);
                long beforeTime = Long.parseLong(nodeValue.split(",")[1]);
                if (System.currentTimeMillis()-beforeTime > 5000){
                    resultPort = Integer.parseInt(children);
                    System.out.println("该服务端实例已超过5s未收到客户端请求，优先路由该服务实例");
                    break;
                }
                //循环，获取所有服务器实例当中响应时间最短的，赋值给tempTime，对应的端口号即代表该服务实例
                if (responseTime <= tempTime){
                    tempTime = responseTime;
                    resultPort = Integer.parseInt(children);
                }
            }
        }

        System.out.println("客户端请求对应服务端：127.0.0.1:"+resultPort);
        try {
            bootstrap.connect("127.0.0.1",resultPort).sync();
        }catch (Exception e){
            initClient();
        }
    }

    //4.编写一个方法，使用JDK的动态代理创建对象
    //serviceClass 接口类型，根据哪个接口子类代理对象； providerParam："UserService#sayHello#"
    public static Object creatProxy(final Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //1）初始化客户端client
 //               if (userClientHandler ==null){
                    initClient();
 //               }

                //2) 给UserClientHandler 设置param参数 封装RpcRequest
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setClassName(serviceClass.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameterTypes(method.getParameterTypes());
                rpcRequest.setParameters(args);
                userClientHandler.setParam(rpcRequest);

                long beforeTime = System.currentTimeMillis();
                //3）使用线程池，开启一个线程处理call() 写操作，并返回结果
                Object result = executorService.submit(userClientHandler).get();
                long endTime = System.currentTimeMillis();
                long responseTime = endTime-beforeTime;
                ConsumerBoot.zkClient.writeData("/rpcServer/"+resultPort,responseTime+","+beforeTime);

                //4）return 结果
                return result;
            }
        });
    }
}
